package processor;

import com.sun.org.apache.bcel.internal.generic.Select;
import model.BaseInvestment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;
import util.MyString;
import util.Mytime;
import util.addTargetRequest;

import java.util.ArrayList;
import java.util.List;



public class BasePageInvestmentProcessor {
    public static Logger logger = LoggerFactory.getLogger("BasePageInvestmentProcessor");

    public static void processFirmBaseInvestment(Page page){
        /**
         * @Description 因为涉及到翻页，请求xhr对象，解析获得相应的数据项目。
         * 如果该页面有“>”标志，说明还有下一页，此时page_id+1请求加1
         */

//        if(isRedirectedToLoginPage(page)){
//            page.addTargetRequest(page.getRequest());
//            return;
//        }
        // webmagic 这里直接选择节点/不好用，只能先用css选择器
        // 判断是否有table

        List<Selectable> ntableNodes = page.getHtml().$("table[class~=ntable]").nodes();
        if (ntableNodes.size() == 0){
            logger.info("无投资关系");
            return;
        }else {
            List<Selectable> nodes = ntableNodes.get(0).xpath("/table/tbody/tr").nodes();
            List<BaseInvestment> baseInvestments = new ArrayList<BaseInvestment>();
            if(nodes.size()>1){
                for(int i = 1;i < nodes.size();i++){
                    Selectable node = nodes.get(i);
                    BaseInvestment baseInvestment = new BaseInvestment();
                    baseInvestment.setCompany_unique(page.getRequest().getExtra("unique").toString());
                    baseInvestment.setInvestment_unique(node.xpath("/tr/td").nodes().get(1).xpath("//td/a/@href").toString()
                            .replace("/firm_","")
                            .replace(".html",""));
                    // 切割空格，获得投资名称
                    baseInvestment.setInvestment_name(MyString.Replace(node.xpath("/tr/td").nodes().get(1).xpath("//td/a/h3/allText()").toString().split(" ")[0]));
                    // 切割空格，获得法人名称
                    baseInvestment.setInvestment_people(node.xpath("/tr/td").nodes().get(2).xpath("//td/allText()").toString().split(" ")[0]);
                    baseInvestment.setRegistered_capital(node.xpath("/tr/td").nodes().get(3).xpath("/td/allText()").toString());
                    baseInvestment.setFunded_ratio(node.xpath("/tr/td").nodes().get(4).xpath("/td/allText()").toString());
                    baseInvestment.setEstablishment_date(node.xpath("/tr/td").nodes().get(5).xpath("/td/allText()").toString());
                    baseInvestment.setStatus(node.xpath("/tr/td").nodes().get(6).xpath("/td/allText()").toString());

                    baseInvestment.setCreatedTime(Mytime.getTime());
//                System.out.println(baseInvestment);
                    //如果当前优先级大于边界优先级 抓取下一层级投资关系
                    if (page.getRequest().getPriority()-1>=
                            Integer.valueOf(page.getRequest().getExtra("InitialPriority").toString())
                                    -Integer.valueOf(page.getRequest().getExtra("MinInvestmentPriority").toString())){
                        addTargetRequest.add(page,
                                "https://www.qichacha.com/firm_"+baseInvestment.getInvestment_unique()+".html#base",
                                baseInvestment.getInvestment_name(),
                                page.getRequest().getPriority()-1);
                    }

                    baseInvestments.add(baseInvestment);
                }
            }
            page.putField("BaseInvestment",baseInvestments);

            String unique = page.getRequest().getExtra("unique").toString();
            String company_name = page.getRequest().getExtra("company_name").toString();

            // 判断页面是否有">"标准，如果有，则当前页面加1，抓取优先级-1
            List<Selectable> pageIdList = page.getHtml().xpath("//ul[@class='pagination']//a[@id='ajaxpage']/allText()").nodes();
            for (Selectable pageId:pageIdList){
                if (pageId.toString().contains(">")){
                    Request r = page.getRequest();
                    int next_page_id = Integer.valueOf(r.getExtra("page_id").toString())+1;
//                System.out.println("下一页:"+next_page_id);
                    addTargetRequest.add(page,unique,
                            company_name,
                            "base",
                            "touzi",
                            next_page_id,
                            page.getRequest().getPriority()-1);
                    break;
                }
            }
        }

    }


}
